<?php
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------

namespace app\services\order;


use app\dao\order\StoreOrderDao;
use app\services\activity\lottery\LuckLotteryServices;
use app\services\activity\combination\StorePinkServices;
use app\services\BaseServices;
use app\services\pay\PayServices;
use app\services\user\UserMoneyServices;
use app\services\user\UserServices;
use crmeb\exceptions\ApiException;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

/**
 * Class StoreOrderSuccessServices
 * @package app\services\order
 * @method getOne(array $where, ?string $field = '*', array $with = []) 获取去一条数据
 */
class StoreOrderSuccessServices extends BaseServices
{
    /**
     *
     * StoreOrderSuccessServices constructor.
     * @param StoreOrderDao $dao
     */
    public function __construct(StoreOrderDao $dao)
    {
        $this->dao = $dao;
    }

    /**
     * 0元支付
     * @param array $orderInfo
     * @param int $uid
     * @return bool
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function zeroYuanPayment(array $orderInfo, int $uid, string $payType = PayServices::YUE_PAY)
    {
        if ($orderInfo['paid']) {
            throw new ApiException(410265);
        }
        return $this->paySuccess($orderInfo, $payType);//余额支付成功
    }

    /**
     * 支付成功
     * @param array $orderInfo
     * @param string $paytype
     * @param array $other
     * @return bool
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function paySuccess(array $orderInfo, string $paytype = PayServices::WEIXIN_PAY, array $other = [])
    {
        $updata = ['paid' => 1, 'pay_type' => $paytype, 'pay_time' => time()];
        $orderInfo['pay_time'] = $updata['pay_time'];
        $orderInfo['pay_type'] = $paytype;
        if ($other && isset($other['trade_no'])) {
            $updata['trade_no'] = $other['trade_no'];
        }
        /** @var StoreOrderCartInfoServices $orderInfoServices */
        $orderInfoServices = app()->make(StoreOrderCartInfoServices::class);
        $orderInfo['storeName'] = $orderInfoServices->getCarIdByProductTitle((int)$orderInfo['id']);
        $res1 = $this->dao->update($orderInfo['id'], $updata);
        $resPink = true;
        if ($orderInfo['combination_id'] && $res1 && !$orderInfo['refund_status']) {
            /** @var StorePinkServices $pinkServices */
            $pinkServices = app()->make(StorePinkServices::class);
            /** @var StoreOrderServices $orderServices */
            $orderServices = app()->make(StoreOrderServices::class);
            $resPink = $pinkServices->createPink($orderServices->tidyOrder($orderInfo, true));//创建拼团
        }
        //保单产品设置VIP 合伙人等级
        [$level, $integral] = $orderInfoServices->getCartProductIntegral((int)$orderInfo['id']);

        /** @var UserServices $userSrv */
        $userSrv = app()->make(UserServices::class);
        $user = $userSrv->getUserInfo($orderInfo['uid']);
        if ($level){
            $balance = bcadd($user['integral'], $integral, 0);
            $userSrv->update($orderInfo['uid'], ['partner_level'=>$level, 'integral'=>$balance]);
            $userSrv->setMemberOverdueTime(10000, $orderInfo['uid'], 1, 'ever');
            /** @var OrderBonusServices $bonusSrv */
            $bonusSrv = app()->make(OrderBonusServices::class);
            $bonusSrv->addOrderBonus($orderInfo['id'], $orderInfo['uid'], $integral);
        }

        //直推奖励
        if ($user['spread_uid']){
            $parent = $userSrv->getUserInfo($user['spread_uid']);
            $reward = bcmul($orderInfo['total_price'], '0.1', 2);
            if ($reward){
                /** @var UserMoneyServices $moneySrv */
                $moneySrv = app(UserMoneyServices::class);
                $balance = bcadd($parent['now_money'], $reward, 2);
                $userSrv->update($parent['uid'], ['now_money'=>$balance]);
                $moneySrv->income('spread_reward', $parent['uid'], $reward, $balance, $orderInfo['id']);
            }
        }
        //团队奖励
        $totalPrice = $orderInfo['total_price'];
        /** @var StoreOrderCartInfoServices $cartSrv */
        $cartSrv = app()->make(StoreOrderCartInfoServices::class);
        $cashNum = $cartSrv->getCashNum($orderInfo['id']);
        if ($cashNum){
            $totalPrice = bcsub($totalPrice, $cashNum, 2);
        }
        $this->distributePointsToSuperiors($orderInfo['uid'], $totalPrice);

        //缓存抽奖次数 除过线下支付
        if (isset($orderInfo['pay_type']) && $orderInfo['pay_type'] != 'offline') {
            /** @var LuckLotteryServices $luckLotteryServices */
            $luckLotteryServices = app()->make(LuckLotteryServices::class);
            $luckLotteryServices->setCacheLotteryNum((int)$orderInfo['uid'], 'order');
        }
        $orderInfo['send_name'] = $orderInfo['real_name'];
        //订单支付成功后置事件
        event('OrderPaySuccessListener', [$orderInfo]);
        //用户推送消息事件
        event('NoticeListener', [$orderInfo, 'order_pay_success']);
        //支付成功给客服发送消息
        event('NoticeListener', [$orderInfo, 'admin_pay_success_code']);
        // 推送订单
        event('OutPushListener', ['order_pay_push', ['order_id' => (int)$orderInfo['id']]]);

        //自定义消息-订单支付成功
        $orderInfo['time'] = date('Y-m-d H:i:s');
        $orderInfo['phone'] = $orderInfo['user_phone'];
        event('CustomNoticeListener', [$orderInfo['uid'], $orderInfo, 'order_pay_success']);

        //自定义事件-订单支付
        event('CustomEventListener', ['order_pay', [
            'uid' => $orderInfo['uid'],
            'id' => (int)$orderInfo['id'],
            'order_id' => $orderInfo['order_id'],
            'real_name' => $orderInfo['real_name'],
            'user_phone' => $orderInfo['user_phone'],
            'user_address' => $orderInfo['user_address'],
            'total_num' => $orderInfo['total_num'],
            'pay_price' => $orderInfo['pay_price'],
            'pay_postage' => $orderInfo['pay_postage'],
            'deduction_price' => $orderInfo['deduction_price'],
            'coupon_price' => $orderInfo['coupon_price'],
            'store_name' => $orderInfo['storeName'],
            'add_time' => date('Y-m-d H:i:s', $orderInfo['add_time']),
        ]]);

        $res = $res1 && $resPink;
        return false !== $res;
    }
    
    public function getRewardRatio($level)
    {
        $data[0] = '0.1';
        $data[1] = '0.13';
        $data[2] = '0.16';
        $data[3] = '0.19';
        $data[4] = '0.22';
        return $data[$level] ?? 0;
    }

    /**
     * 给上级分配积分
     * @param $uid
     * @param $integral
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    private function distributePointsToSuperiors($uid, $integral)
    {
        $totalPoints = 12; // 总共需要分配的积分
        $distributedPoints = 0; // 已分配积分

        $currentUid = $uid;
        $processedUsers = []; // 记录已处理的用户，防止循环引用

        /** @var UserMoneyServices $moneySrv */
        $moneySrv = app()->make(UserMoneyServices::class);
        /** @var UserServices $userSrv */
        $userSrv = app()->make(UserServices::class);

        while ($distributedPoints < $totalPoints) {
            // 获取当前用户的上级
            $currentUser = $userSrv->getUserInfo($currentUid);

            if (!$currentUser || !$currentUser['spread_uid']) {
                break; // 没有上级，停止分配
            }

            // 获取上级信息
            $superior = $userSrv->getUserInfo($currentUser['spread_uid']);

            if (!$superior) {
                break; // 上级不存在，停止分配
            }

            // 防止循环引用
            if (in_array($superior['uid'], $processedUsers)) {
                break;
            }
            $processedUsers[] = $superior['uid'];

            // 计算该上级应得的积分
            $pointsToGive = $this->calculatePoints((int)$superior['level'], $distributedPoints, $totalPoints);

            if ($pointsToGive > 0) {
                // 给上级增加积分
                $ratio = bcdiv($pointsToGive, '100', 2);
                $money = bcmul($integral, $ratio, 2);
                $balance = bcadd($superior['now_money'], $money, 2);

                $distributedPoints += $pointsToGive;
                $userSrv->update($superior['uid'], ['now_money'=>$balance]);
                $moneySrv->income('spread_reward', $superior['uid'], $money, $balance, $uid);
            }

            // 移动到上一级
            $currentUid = $superior['uid'];
        }
    }

    /**
     * 计算上级应得的积分
     * @param int $level 上级等级
     * @param int $distributedPoints 已分配积分
     * @param int $totalPoints 总积分
     * @return int
     */
    private function calculatePoints(int $level, int $distributedPoints, int $totalPoints)
    {
        // 各等级对应的基础积分
        $levelPoints = [
            1 => 3,
            2 => 6,
            3 => 9,
            4 => 12
        ];

        // 该等级应得的基础积分
//        $basePoints = $levelPoints[$level] ?? 0;
        if (!isset($levelPoints[$level])){
            return 0;
        }

        // 计算实际可分配的积分（考虑剩余积分）
        $remainingPoints = $totalPoints - $distributedPoints;

        if ($remainingPoints <= 0) {
            return 0;
        }

        // 如果剩余积分小于该等级应得积分，则分配剩余积分
//        if ($remainingPoints < $basePoints) {
//            return $remainingPoints;
//        }

        // 计算该等级实际能得到的积分（基于规则）
        // 规则：每个等级实际得到的是其基础积分与前面等级差值的累积
        $actualPoints = $levelPoints[$level] - $distributedPoints;
        if ($actualPoints <= 0){
            return 0;
        }
//        for ($i = 1; $i < $level; $i++) {
//            $actualPoints -= ($levelPoints[$i] ?? 0);
//        }

        // 确保不超过剩余积分
        return min($actualPoints, $remainingPoints);
    }

}
